package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecService {

    @Autowired
    private SpecGroupMapper groupMapper;

    @Autowired
    private SpecParamMapper paramMapper;

    public List<SpecGroupDTO> querySpecGroupByCategory(Long id) {
        // 查询数据
        SpecGroup group = new SpecGroup();
        group.setCid(id);
        List<SpecGroup> list = groupMapper.select(group);
        // 非空判断
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        // 转换DTO
        return BeanHelper.copyWithCollection(list, SpecGroupDTO.class);
    }

    public List<SpecParamDTO> queryParams(Long gid, Long cid, Boolean searching) {
        // 健壮性处理
        if (gid == null && cid == null) {
            // 没有查询参数，返回400
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        // 查询参数
        SpecParam param = new SpecParam();
        param.setGroupId(gid);
        param.setCid(cid);
        param.setSearching(searching);
        List<SpecParam> list = paramMapper.select(param);
        // 非空判断
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        // 转换DTO
        return BeanHelper.copyWithCollection(list, SpecParamDTO.class);
    }

    public List<SpecGroupDTO> querySpecList(Long id) {
        // 根据分类id查询group的集合
        List<SpecGroupDTO> groupList = querySpecGroupByCategory(id);
        // 查询出分类下的所有参数
        List<SpecParamDTO> params = queryParams(null, id, null);
        // 把params按照groupId做分组，groupId一致的放到一个集合。变成一个map，key是groupId,值是param集合
        Map<Long, List<SpecParamDTO>> map = params.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        // 根据groupId查询参数
        for (SpecGroupDTO group : groupList) {
            group.setParams(map.get(group.getId()));
        }
        return groupList;
    }
}
